#include "fonts_manager.h"
#include "config.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>

int GBKFontInit(char *pcFontFile, unsigned int dwFontSize);
int GBKGetFontBitmap(unsigned int dwCode, PT_FontBitMap ptFontBitMap);
static unsigned char *g_pucHZKMem;
static unsigned char *g_pucHZKMemEnd;
static T_FontOpr g_tGBKFontOpr = {
    .name = "gbk",
    .FontInit = GBKFontInit,
    .GetFontBitmap = GBKGetFontBitmap};

int GBKFontInit(char *pcFontFile, unsigned int dwFontSize)
{
    struct stat tStat;
    int ret;
    if (16 != dwFontSize)
    {
        DBG_PRINTF("GBK can't support %d fontsize\n", dwFontSize);
        return -1;
    }
    int g_iFdHZK = open(pcFontFile, O_RDONLY);
    if (g_iFdHZK)
    {
        DBG_PRINTF("GBKFont file open error! \n");
    }
    ret = stat(pcFontFile, &tStat);
    if (ret)
    {
        DBG_PRINTF("GBKFont file get size error! \n");
    }
    g_pucHZKMem = mmap(NULL, tStat.st_size, PROT_READ, MAP_SHARED, g_iFdHZK, 0);
    if (g_pucHZKMem == (unsigned char *)-1)
    {
        DBG_PRINTF("GBKFont file mmap error! \n");
    }
    g_pucHZKMemEnd = g_pucHZKMem + tStat.st_size;
    return 0;
}

int GBKGetFontBitmap(unsigned int dwCode, PT_FontBitMap ptFontBitMap)
{
    int iArea;
    int iWhere;
    int iPenX = ptFontBitMap->iCurOriginX;
    int iPenY = ptFontBitMap->iCurOriginY;

    if (dwCode & 0xffff0000)
    {
        DBG_PRINTF("don't support this code : 0x%x\n", dwCode);
        return -1;
    }
 
    iArea = ((dwCode >> 8) & 0xff) - 0xA1;
    iWhere = (dwCode & 0xff) - 0xA1;
    if ((iArea < 0) || (iWhere < 0))
    {
        DBG_PRINTF("%s %s %d\n", __FILE__, __FUNCTION__, __LINE__);
        return -1;
    }
    ptFontBitMap->iXLeft = iPenX;
    ptFontBitMap->iYTop = iPenY - 16;
    ptFontBitMap->iXMax = iPenX + 16;
    ptFontBitMap->iYMax = iPenY;
    ptFontBitMap->pucBuffer = g_pucHZKMem + 94*iArea*32+iWhere*32;
    if (ptFontBitMap->pucBuffer >= g_pucHZKMemEnd)
	{
		return -1;
	}
    ptFontBitMap->iBpp = 1;
    ptFontBitMap->iPitch = 2;
	ptFontBitMap->iNextOriginX = iPenX + 16;
	ptFontBitMap->iNextOriginY = iPenY;

    return 0;
}
int GBKInit(void)
{
	return RegisterFontOpr(&g_tGBKFontOpr);
}

